import fs from 'fs-extra';
import fg from 'fast-glob';
import ini from 'ini';
import path from 'path';
import { env } from '../env.js';

interface ProjectCfg {
    Project: {
        code: string,
        Name: string, 
        Alias?: string,
        ProjectType?: 'H5ts' | 'Unity' | 'Laya',
        chatid?: string
    }, 
    Svn: {
        ClientSvn: string, 
        DesignerSvn: string, 
        SvrSvn: string
    },
    Build?: {
        ProjRoot: string
    }
}

export class ProjIniCfgParser {
    /**
     * 通过项目中文名获取其ini配置。
     * @param projectName 
     * @returns 
     */
    async getProjIniCfg(projectName: string): Promise<ProjectCfg | null> {
            if (env.projIniRoot && fs.existsSync(env.projIniRoot)) {
                const inis = fg.sync(['*.ini', '*.json'], { cwd: env.projIniRoot, ignore: ['all.svn.json']});
                for (const i of inis) {
                    const icontent = fs.readFileSync(path.join(env.projIniRoot, i), 'utf-8');
                    const iext = path.extname(i);
                    let iCfg: ProjectCfg;
                    if (iext == '.json') {
                        iCfg = JSON.parse(icontent);
                    } else {
                        iCfg = ini.parse(icontent) as ProjectCfg;
                    }
                    if (iCfg.Project.Name == projectName || iCfg.Project.Alias == projectName) {
                        iCfg.Project.code = path.basename(i, iext);
                        return iCfg;
                    }
                }
            }
            return null;
    }
}
